package com.lingyu.jsjx.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.lingyu.jsjx.domain.FileInfo;
import com.lingyu.jsjx.domain.vo.UserDocumentVO;
import com.ruoyi.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.lingyu.jsjx.domain.UserDocument;
import com.lingyu.jsjx.service.IUserDocumentService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 文档管理Controller
 *
 * @author ruoyi
 * @date 2025-07-31
 */
@RestController
@RequestMapping("/userDocument")
@Api(tags = "文档管理管理")
public class UserDocumentController extends BaseController {
    @Autowired
    private IUserDocumentService userDocumentService;

    /**
     * 查询文档管理列表
     */
    @RequiresPermissions("jsjx:userDocument:list")
    @GetMapping("/list")
    @ApiOperation("查询文档管理列表")
    public TableDataInfo list(UserDocument userDocument) {
        startPage();
        List<UserDocument> list = userDocumentService.selectUserDocumentList(userDocument);
        return getDataTable(list);
    }

    @RequiresPermissions("jsjx:userDocument:shareList")
    @GetMapping("/shareList")
    @ApiOperation("查询共享文档管理列表")
    public TableDataInfo shareList(@RequestParam(value = "majorId", required = false) Long majorId, @RequestParam(value = "wordTitle", required = false) String wordTitle, @RequestParam(value = "deptId", required = false) String deptId, @RequestParam(value = "categoryId", required = false) String categoryId) {
        startPage();
        List<UserDocumentVO> list = userDocumentService.selectSharedDocuments(majorId, wordTitle, deptId, categoryId, SecurityUtils.getUserId());
        return getDataTable(list);
    }

    /**
     * 导出文档管理列表
     */
    @RequiresPermissions("jsjx:userDocument:export")
    @Log(title = "文档管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出文档管理列表")
    public void export(HttpServletResponse response, UserDocument userDocument) {
        List<UserDocument> list = userDocumentService.selectUserDocumentList(userDocument);
        ExcelUtil<UserDocument> util = new ExcelUtil<UserDocument>(UserDocument.class);
        util.exportExcel(response, list, "文档管理数据");
    }

    /**
     * 获取文档管理详细信息
     */
    @RequiresPermissions("jsjx:userDocument:query")
    @GetMapping(value = "/{wordId}")
    @ApiOperation("文档管理详细")
    public AjaxResult getInfo(@PathVariable("wordId") Long wordId) {
        return success(userDocumentService.selectUserDocumentByWordId(wordId));
    }

    /**
     * 新增文档管理
     */
    @RequiresPermissions("jsjx:userDocument:add")
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated UserDocument userDocument) {
        return toAjax(userDocumentService.insertUserDocument(userDocument));
    }

    /**
     * 修改文档管理
     */
    @RequiresPermissions("jsjx:userDocument:edit")
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改文档管理")
    public AjaxResult edit(@RequestBody @Validated UserDocument userDocument) {
        return toAjax(userDocumentService.updateUserDocument(userDocument));
    }

    @RequiresPermissions("jsjx:userDocument:edit")
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @RequestMapping("/downloadUserDocument")
    @ApiOperation("修改文档管理下载数")
    public void downloadUserDocument(@RequestParam("wordId") Long wordId, HttpServletResponse response) {
        UserDocument userDocument = userDocumentService.selectUserDocumentByWordId(wordId);
        int downloadNum = userDocument.getDownloadNum();
        userDocument.setDownloadNum(downloadNum + 1);
        userDocumentService.updateUserDocument(userDocument);
        List<FileInfo> fileInfoList = userDocument.getFileInfo();
        // 实现打包下载逻辑
        try {
            // 设置响应头
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"documents.zip\"");

            // 创建ZIP输出流
            try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
                for (FileInfo fileInfo : fileInfoList) {
                    String fileUrl = fileInfo.getFileUrl();
                    // 根据fileUrl获取文件输入流
                    InputStream inputStream = getFileInputStream(fileUrl);
                    if (inputStream != null) {
                        // 添加文件到ZIP
                        ZipEntry zipEntry = new ZipEntry(getFileNameFromUrl(fileUrl));
                        zipOut.putNextEntry(zipEntry);

                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = inputStream.read(bytes)) >= 0) {
                            zipOut.write(bytes, 0, length);
                        }
                        zipOut.closeEntry();
                        inputStream.close();
                    }
                }
                zipOut.finish();
            }
            userDocumentService.updateUserDocument(userDocument);
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
        }
    }

    // 示例方法：根据文件URL获取输入流
    private InputStream getFileInputStream(String fileUrl) throws Exception {
        // 构造实际文件路径
        String basePath = System.getProperty("user.dir"); // 获取项目根目录
        String realPath = basePath + "/uploadFile" + fileUrl.replace("/statics", ""); // 拼接完整路径
        File file = new File(realPath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在: " + realPath);
        }

        return new FileInputStream(file);
    }

    // 示例方法：从URL中提取文件名
    private String getFileNameFromUrl(String fileUrl) {
        // 提取文件名部分
        String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
        try {
            // URL解码，处理可能的中文文件名
            return java.net.URLDecoder.decode(fileName, "UTF-8");
        } catch (Exception e) {
            return fileName;
        }
    }

    /**
     * 删除文档管理
     */
    @RequiresPermissions("jsjx:userDocument:remove")
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{wordIds}")
    @ApiOperation("删除文档管理")
    public AjaxResult remove(@PathVariable Long[] wordIds) {
        return toAjax(userDocumentService.deleteUserDocumentByWordIds(wordIds));
    }

    @GetMapping(value = "/queryUserDocumentUpDownCount")
    public AjaxResult queryUserDocumentUpDownCount() {
        return success(userDocumentService.selectUserDocumentUpDownCount());
    }
}
